'use strict';
var Promise = require('/promise.js')
var modal = require('/modal.js')
var auth = require('/auth.js')
var storage = require('/storage.js')

var project = require('../conf.js');

var host = project.domain;

module.exports = {
    get(url,data) {
        var req = function(resolve){
            return new Promise((resolve2, reject2) => {
                wx.request({
                    url: host+url,
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    success: function(res) {
                        resolve(res)
                        
                    },
                    fail: function(res) {
                        reject2(res)
                    }
                })
            })
        }
        return new Promise((resolve, reject) => {
            auth.login().then(function(){
                return req(resolve);
            });
        });
        
    },
    post(url, data) {
        var req = function(resolve,reject){
            return new Promise((resolve2,reject2)=>{
                var sessionId = wx.getStorageSync('sessionId');
                var authObj ={
                    wx_session:sessionId
                };
                if(!!url.domain){
                    host = url.domain;
                }
                for(var key in data){
                    data[key]['wx_session'] = sessionId;
                    // data[key] = Object.assign(data[key],authObj);
                }
                var reqNum = 0;
                var reqFunc = function(){
                    wx.request({
                        url: host+url.path,
                        data: data,
                        method: 'POST',
                        headers: {
                            'Cache-Control': 'no-cache',
                            'Content-Type': 'application/x-www-form-urlencode;charset=UTF-8;'
                        },
                        success: function(res) {
                            var retData = res.data;
                            if(!retData.ret){
                                resolve(retData.data)
                            }else{
                                if(retData.errorcode == '-1001'){
                                    reqNum++;
                                    if(reqNum >= 3){
                                        modal.toast('服务器异常');
                                        return;
                                    }
                                    storage.remove('sessionId',function(){
                                        auth.login().then(function(){
                                            console.log('-1001')
                                            reqFunc();
                                        },function(){

                                        });
                                    });
                                    
                                }else{
                                    modal.toast(retData.msg);
                                }
                            }
                        },
                        fail: function(res) {
                            reject(res)
                        }
                    });
                }
                reqFunc();
            });
        } 
        return new Promise((resolve, reject) => {
            auth.login().then(function(){
                return req(resolve,reject);
            });
        });
    },
    json2Form(json) {
        var str = []
        for (var p in json) {
            str.push(encodeURIComponent(p) + "=" + encodeURIComponent(json[p]))
        }
        return str.join("&")
    },
    // 绑定手机号
    bind() {
        return new Promise((resolve, reject) => {
            var need_bind = wx.getStorageSync('need_bind') || '1';
            var no_bind_time = wx.getStorageSync('no_bind_time');
            var no_bind = false;

            var currentPages = getCurrentPages();
            var currentPage = currentPages[currentPages.length - 1];
            var no_bind_src_uc = wx.getStorageSync('no_bind_src_uc');
            if(currentPage.route == 'pages/center/center') { // 进入个人中心
                no_bind = no_bind_src_uc ? true : false;
                wx.setStorageSync('no_bind_src_uc', '1');
            }

            if (no_bind_time) {// 在今天以前残忍拒绝绑定手机号
                var d = new Date(no_bind_time).getDate();
                var d0 = new Date().getDate();
                if (d == d0) {
                    no_bind = true;
                }
                else {// 超过一天
                    wx.setStorageSync('no_bind_src_uc', '');
                }
            }

            if (!no_bind && need_bind == '1') {
                this.post({
                    path: '/wxapp_api/api'
                },{
                    'self:sms:bindinfo': {}
                }).then((res) => {
                    var bindRes = res['self:sms:bindinfo']
                    if(bindRes.ret == 0) {
                        var bindData = bindRes.data
                        if(bindData.need_bind == 1) {
                            // 需要绑定
                            wx.navigateTo({
                                url: "../no-link/no-link?tel=" + bindData.address_mobile + "&current="+ currentPage.route
                            })
                        }
                        else {
                            wx.setStorageSync('need_bind', '0')
                            resolve()
                        }
                    }
                    else {
                        resolve()
                    }
                })
            } 
            else{
                resolve()
            }
        });
    },
    nobind() { // “残忍拒绝”绑定手机号
        wx.setStorageSync('no_bind_time', +new Date)
    }
}
